package com.example.project.projectspringcloud.utils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/6/6 0006.
 */
public class EnterpriseSmsUtil {

    private String MNSEndpoint = "http://dx1.xitx.cn:8888/sms.aspx";

    private String accessId = "";
    private String acacessKey = "";
    private String userId = "";

    public EnterpriseSmsUtil(String accessId, String acacessKey, String userId) {
        this.accessId = accessId;
        this.acacessKey = acacessKey;
        this.userId = userId;
    }

    /**
     * 发送短信
     *
     * @param signName        签名
     * @param messageBody     消息内容包含参数   如:   您的验证码是${code}.
     * @param parameterValues 参数的值
     * @param phone           电话号码
     * @return
     */
    public String sendmsg(String phone, String signName, String messageBody, String... parameterValues) {
        // 读取短信参数并赋值
        List<String> parameterNames = analysisParameter(messageBody);
        int length = parameterValues.length;
        for (int i = 0; i < length; i++) {
            // 短信的参数,和传入的参数不一致,此处可能下标越界(以传入的参数个数为准)
            String parameterValue = parameterValues[i];
            if (parameterNames.size() != 0) {
                String parameterName = parameterNames.get(i);
                messageBody = messageBody.replace(parameterName, parameterValue);
            }
        }
        Map map = new LinkedHashMap();
        map.put("userid", userId);
        map.put("account", accessId);
        map.put("password", acacessKey);
        map.put("mobile", phone);
        map.put("content", messageBody + signName);
        map.put("sendTime", "");
        map.put("action", "send");
        map.put("checkcontent", "0");
        String result = HttpUtil.post(MNSEndpoint, map);

        return "{\"result\":\"0\"}";
    }

    /**
     * 找出所有参数
     *
     * @param messageBody
     * @return
     */
    private List<String> analysisParameter(String messageBody) {
        String regex = "\\{([^\\}]*)\\}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(messageBody);
        List<String> list = new ArrayList<>();
        while (matcher.find()) {
            String group = matcher.group(0);
            list.add(group);
        }
        return list;
    }

    public static void main(String[] args) {
        EnterpriseSmsUtil smsUtil = new EnterpriseSmsUtil("7975", "a10709", "110709");
        smsUtil.sendmsg("15027733219", "【盈丰力胜】",
                "您的验证码是{code}。请您在3分钟之内完成验证，如非本人操作，请忽略本信息。（yycareer职业咨询平台）", "6666");
    }
}